package org.nhindirect.stagent;

import org.nhindirect.stagent.ProtocolException.ProtocolError;

public class Header extends EntityPart 
{
    String m_name;
    String m_value;
    boolean m_parsed;

    public Header(StringSegment segment)
    {
        super(EntityPartType.Header, segment);
    	this.m_parsed = false;
    }
    
    public Header(String name, String value)
    {
    	super(EntityPartType.Header);    		
        this.setText(Protocol.combine(name, value));
        this.m_name = name;
        this.m_value = value;
        this.m_parsed = true;
    }
    
    /// <summary>
    /// The Text should contain a ':' separator
    /// Assumes that the text is otherwise well formed. 
    /// </summary>
    @Override
    public String getText()
    {
       return super.getText();
    }
     
    @Override
    public void setText(String value) 
    {
    	super.setText(value);
        this.m_parsed = false;
    }

    public String getName()
    {
    	this.ensureNameValue();
        return this.m_name;
    }

    public String getValue()
    {
	    this.ensureNameValue();
	    return this.m_value;    
    }
    
    @Override 
    protected void appendSourceText(StringSegment segment)
    {
        if (!this.getSourceText().isNull())
        {
            //
            // Header already has text. We need to unfold the new text in...
            //
            StringSegment unfoldedLine = EntityParser.skipWhitespace(segment);
            if (unfoldedLine.isEmpty())
            {
                throw new ProtocolException(ProtocolError.InvalidHeader);
            }
            super.appendText(unfoldedLine.toString());
        }

        super.appendSourceText(segment);
    }

    void ensureNameValue()
    {
        if (this.m_parsed)
        {
            return;
        }

        String headerText = this.getText();
        int separatorPosition = EntityParser.findChar(new StringSegment(headerText), Protocol.NameValueSeparator, true);            
        if (separatorPosition < 0)
        {
            throw new ProtocolException(ProtocolError.MissingNameValueSeparator);
        }
        if (separatorPosition == 0)
        {
            throw new ProtocolException(ProtocolError.InvalidHeader);
        }
        this.m_name = headerText.substring(0, separatorPosition);
        separatorPosition++;
        
        if (separatorPosition == headerText.length())
        {
            throw new ProtocolException(ProtocolError.MissingHeaderValue);
        }
        
        this.m_value = headerText.substring(separatorPosition).trim();

    }
}
